import type { RouteRecordRaw } from "vue-router";
import type { Menu } from "@/typings";
import { LOGIN_URL } from "@/config";
import router from "@/routers";
import { useAuthStore, useUserStore } from "@/stores";
import { ElNotification } from "element-plus";

const modules = import.meta.glob("@/views/**/*.vue");

/**
 * @description 路由转换
 */
const routeConvert = (menuList: Menu[], layout = "layout") => {
  menuList.forEach((item: Menu) => {
    if (item.component && typeof item.component === "string") {
      item.component = modules["/src/views" + item.component + ".vue"];
    }
    if (item.children && item.children.length > 0) {
      item.component = "";
      routeConvert(item.children, item.name);
    }
    router.addRoute(layout, item as unknown as RouteRecordRaw);
  });
};

/**
 * @description 动态路由
 */
export const initDynamicRouter = async () => {
  const useAuth = useAuthStore();
  const useUser = useUserStore();
  try {
    if (useAuth.userMenu.length <= 0) {
      ElNotification({
        title: "无权限访问",
        message: "当前账号无任何菜单权限，请联系系统管理员！",
        type: "error"
      });
      useUser.clearCacheHandler();
      router.replace(LOGIN_URL);
      return Promise.reject("无权限访问");
    }
    routeConvert(useAuth.userMenu);
  } catch (error) {
    useUser.clearCacheHandler();
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
};
